<?php

namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Api\ApiController;
use App\Http\Requests\Role\StoreRoleRequest;
use App\Http\Requests\Role\UpdateRoleRequest;
use App\Models\Role;
use Illuminate\Http\Request;

class RoleController extends ApiController
{
    public function __construct()
    {
        $this->authorizePermission('manage_roles');
    }

    /**
     * 获取角色列表
     */
    public function index(Request $request)
    {
        $roles = Role::query()
            ->when($request->filled('name'), function ($query) use ($request) {
                $query->where('name', 'like', '%' . $request->name . '%');
            })
            ->when($request->filled('status'), function ($query) use ($request) {
                $query->where('status', $request->status);
            })
            ->with('permissions')
            ->paginate(10);

        return $this->paginate($roles);
    }

    /**
     * 创建角色
     */
    public function store(StoreRoleRequest $request)
    {
        $data = $request->validated();
        $role = Role::create($data);

        return $this->success($role, '创建成功');
    }

    /**
     * 获取角色详情
     */
    public function show(Role $role)
    {
        $role->load('permissions');

        return $this->success($role);
    }

    /**
     * 更新角色
     */
    public function update(UpdateRoleRequest $request, Role $role)
    {
        $data = $request->validated();
        $role->update($data);

        return $this->success($role, '更新成功');
    }

    /**
     * 删除角色
     */
    public function destroy(Role $role)
    {
        // 不能删除超级管理员角色
        if ($role->slug === 'super_admin') {
            return $this->error('不能删除超级管理员角色');
        }

        $role->delete();

        return $this->success(null, '删除成功');
    }

    /**
     * 为角色分配权限
     */
    public function assignPermissions(Role $role, Request $request)
    {
        $request->validate([
            'permissions' => 'required|array',
            'permissions.*' => 'exists:permissions,id',
        ]);

        $role->permissions()->sync($request->permissions);

        return $this->success(null, '权限分配成功');
    }
}
